package org.zk.dubbo_consumer.secutity;


import lombok.Getter;
import lombok.Setter;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.LoggerFactory;
import org.zk.dubbo_consumer.util.DESUtil;
import org.zk.dubbo_consumer.util.PhoneOrMail;
import org.zk.entity.Teacher;
import org.zk.entity.User;
import org.zk.service.TeacherService;
import org.zk.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class MyShiroRealm extends AuthorizingRealm {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    //如果项目中用到了事物，@Autowired注解会使事物失效，可以自己用get方法获取值
    @Resource
    @Getter
    @Setter
    private UserService userService;

    @Resource
    @Getter
    @Setter
    private HttpServletRequest request;

    @Resource
    @Getter
    @Setter
    private TeacherService teacherService;

    /**
     * 认证信息.(身份验证)：Authentication是用来验证用户身份
     *
     * @param authenticationToken
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        HttpSession session=request.getSession();


        /**
         * 以下是登录---------------------------------------------------------------------------------------------------------------------------
         */
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;     //user
        String teacherPhone = "";
        String teacherPassword = "";
        Teacher teacher = new Teacher();
        Teacher teacher1 = new Teacher();
        if (request.getRequestURI().equals("/teacherPhoneLoginDes")) {
            try {
                teacherPhone = token.getUsername();
                teacherPassword = String.valueOf(token.getPassword());
                boolean re = PhoneOrMail.isPhoneOrMail(teacherPhone);
                if (re) {
                    teacher.setTeacherEmail(teacherPhone);
                    teacher.setTeacherPwd(teacherPassword);
                    teacher1 = teacherService.getTeacherLoginByEmail(teacher);
                    teacher1.setTeacherPwd(DESUtil.decryptBasedDes(teacherPassword));
                } else {
                    String tPassword = DESUtil.encryptBasedDes(teacherPassword);
                    String tPhone = DESUtil.encryptBasedDes(teacherPhone);
                    teacher.setTeacherPhone(tPhone);
                    teacher.setTeacherPwd(tPassword);
                    //从数据库获取对应用户名密码的用户
                    teacher1 = teacherService.getTeacherLogin(teacher);
                    teacher1.setTeacherPhone(teacherPhone);
                    teacher1.setTeacherPwd(teacherPassword);
                }
                if (teacher1 != null) {
                    logger.info("---------------- Shiro 凭证认证成功 ----------------------");
                    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                            teacher1,//用户
                            teacher1.getTeacherPwd(),//密码
                            getName()//realm name
                    );
                    return authenticationInfo;
                }
            } catch (Exception e) {
                    throw new UnauthorizedException();
            }

        } else {

            /**
             * user登录
             */

            String userPhone = "";
            String password = "";
            User user = new User();

            try {
                userPhone = token.getUsername();
                password = String.valueOf(token.getPassword());

                String pwd = DESUtil.encryptBasedDes(password);
                String userPhone1 = DESUtil.encryptBasedDes(userPhone);
                user.setUserPhone(userPhone1);
                user.setUserPwd(pwd);
                //从数据库获取对应用户名密码的用户
                boolean result = PhoneOrMail.isPhoneOrMail(userPhone);
                User userList = new User();
                if (result) {        //邮箱
                    userList = userService.getUserLoginByEmail(user);
                    userList.setUserPwd(DESUtil.decryptBasedDes(userList.getUserPwd()));
                } else {     //手机号
                    userList = userService.getUserLogin(user);
                }
                if (userList != null) {
                    userList.setUserPwd(DESUtil.decryptBasedDes(userList.getUserPwd()));
                    userList.setUserPhone(DESUtil.decryptBasedDes(userList.getUserPhone()));
                    if (userList.getUserName() == null) {//userEnable等于0，用户为禁用状态
                        throw new NullPointerException();
                    }
                    logger.info("---------------- Shiro 凭证认证成功 ----------------------");
                    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                            userList,//用户
                            userList.getUserPwd(),//密码
                            getName()//realm name
                    );
                    return authenticationInfo;
                }else {
                    throw new NullPointerException();
                }
            } catch (Exception e) {

            }
        }

/**
 * 登录完      -----------------------------------------------------------------------------------------------------------------------------
 */

        throw new UnknownAccountException();
    }

    /**
     * 开始授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("---------------- 执行 Shiro 权限获取 ---------------------");
        Object principal = principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        if (principal instanceof User){
//            User user = (User) principal;
//            //通过用户ID获得角色名
//            Set<String> roles = roleService.findRoleNameByUserId(user.getUserId());
//            authorizationInfo.addRoles(roles);
//            //通过用户ID获得权限的url,这些url是这个人可以访问的页面
////            Set<String> permissions = userService.findPermissionsByUserId(user.getUserId());
////            authorizationInfo.addStringPermissions(permissions);
//        }
//        logger.info("---获取到以下权限---");
//        logger.info(authorizationInfo.getStringPermissions().toString());
//        logger.info("---------------- Shiro 权限获取成功 ----------------------");
        return authorizationInfo;
    }

}
